#!/usr/bin/env python
# coding=utf-8

from spiders import fetcherbase,track_db
from vavava import util
from datetime import datetime,timedelta

class FetcherTnt(fetcherbase.FetcherBase):
    def __init__( self, item_id, log ):
        fetcherbase.FetcherBase.__init__(self, item_id=item_id, track_type=fetcherbase.TRACK_TYPE_TNT,log=log)
        self.fetch_url     = r'http://www.tntexpress.com.au/interaction/asps/Trackcon_tntau.asp?id=trackcon.asp'
        self.post_data     = {
            "trackType":"con","inpTextArea":item_id,"TextArea":item_id,"btnTrack.x":"22","btnTrack.y":"13"
        }

        self.charset_1     = r"utf-8"
        self.reg_str       = r'<tr[^>]*>\s*<td[^>]*>(?P<desc>[^<]*)</td>\s*<td[^>]*>(?P<time1>\d{2}/\d{2}/\d{4})</td>\s*<td[^>]*>(?P<time2>\d{2}:\d{2})</td>\s*<td[^>]*>(?P<locate>[^<]*)</td>\s*</tr>'
        self.date_format   = r'%d/%m/%Y %H:%M'

    def _fetch(self):
        result_list = []
        html_data = self.http.Post(self.fetch_url,self.post_data)
        html = html_data.decode(self.charset_1)
        item_infos = util.reg_helper(html,self.reg_str)
        # get item info list from tags
        if len(item_infos) > 0:
            for item_info in item_infos:
                ti_str = item_info[1]+ " " + item_info[2] # '12/11/2012 15:31'
                item = track_db.TrackData.GetInstance(
                    [
                        -1,
                        self.track_type,
                        self.item_id,
                        datetime.strptime( ti_str, self.date_format ),
                        item_info[0].replace('\n\r\t','').replace('\r','').replace('\t', '').strip(),
                        item_info[3].replace('\n\r\t','').replace('\r','').replace('\t', '').strip(),
                        -1,
                        None
                    ]
                )
                if 'delivered' in item.description.lower():
                    item.is_ended = 1
                result_list.append(item)

        self._chk_new_items(result_list)

